<template>
	<uv-navbar :placeholder="true" :fixed="true" :title="title" left-arrow @leftClick="$onClickLeft">
	</uv-navbar>
	<view class="container">
		<view class="tabs">
			<uv-tabs :list="tabsList" @click="onClick"></uv-tabs>
			<view class="itemMain" v-for="(workItem, itemIndex) in orderItemList" :key="itemIndex">
				<!-- 0 单行文本框 -->
				<view class="singlelineInput" v-if="workItem.type === 0">
					<view class="inputTitle">{{ workItem.name }}:</view>
					<input class="input-class" :data-id="workItem.id" :disabled="disabled" :value="workItem.value"
						@input="bindSinglelineInput" placeholder="请输入" />
				</view>
				<!-- 1 多行文本框 -->
				<view class="multilineInput" v-if="workItem.type === 1">
					<view class="txt">{{ workItem.name }}</view>
					<uv-textarea class="areas" placeholder="请输入" v-model="workItem.value" :disabled="disabled"
						@input="textareaInputs">
					</uv-textarea>
				</view>
				<!-- 2 说明文字 -->
				<view class="multilineInput" v-if="workItem.type === 2">
					<view class="txt">{{ workItem.name }}</view>
					<uv-textarea class="areas" placeholder="请输入" v-model="workItem.value" :disabled="disabled"
						@input="textareaInputs">
					</uv-textarea>
				</view>
				<!-- 3 开关选项 -->
				<view class="switch" v-if="workItem.type === 3">
					<text>{{ workItem.name }}</text>
					<uv-switch
						:v-model="workItem.value === '' ? false : workItem.value || workItem.value === 'true' ? true : false"
						:disabled="disabled" @change="switchChange" />
				</view>
				<!-- 4 图片拍照 -->
				<view class="img" v-if="workItem.type === 4 && state != 5">
					<view class="txt">{{ workItem.name }}</view>
					<view class="upload">
						<!-- <image-upload :uploadId="workItem.id" :disabled="disabled" :fileList="fileList"
							@returnAvatar="returnAvatar" /> -->
						<!-- <text>tupian</text> ref="fileUploadRef" -->
						<imageUpload :ref="el => { if (el) uploadRefs[itemIndex] = el }"
							@files-change="(files) => handleFilesChange(itemIndex, files)"
							@upload-complete="(payload) => handleUploadComplete(itemIndex, payload)"
							@delete-file="(payload) => handleDeleteFile(itemIndex, payload)"
							:initialFiles="getInitialFiles(workItem.sort)" />
					</view>
				</view>
				<view class="img" v-if="workItem.type === 4 && state == 5">
					<view class="txt">{{ workItem.name }}</view>
					<view class="upload" v-if="itemIndex == 1">
						<!-- <image-upload :uploadId="workItem.id" deletable="false" :disabled="true" :fileList="fileArr1" /> -->
						<imageUpload ref="fileUploadRef1" />
					</view>
					<view class="upload" v-if="itemIndex == 3">
						<!-- <image-upload :uploadId="workItem.id" :disabled="true" :fileList="fileArr2" /> -->
						<imageUpload ref="fileUploadRef2" />
					</view>
					<view class="upload" v-if="itemIndex == 5">
						<!-- 	<image-upload :uploadId="workItem.id" :disabled="true" :fileList="fileArr3" /> -->
						<imageUpload ref="fileUploadRef3" />
					</view>
				</view>
			</view>
			<view class="btn">

				<uv-button type="primary" @click="saveBtn">保存</uv-button>
				<uv-button type="default" @click="cancelBtn">取消</uv-button>
				<!-- <view class="start" data-type="开始处理" @click="handleBtn" v-if="showStart">开始处理</view>
				<view class="complete" data-type="处理完成" @click="handleBtn" v-if="showComplete">处理完成</view> -->
				<!-- 验证人的两个按钮 -->
				<!-- 	<view class="agree" data-type="同意" @click="handleBtn" v-if="showAgree">同意</view>
				<view class="reject" data-type="拒绝" @click="handleBtn" v-if="showReject">拒绝</view>
				<view class="stop" data-type="终止" @click="handleBtn" v-if="showStop">终止</view> -->
			</view>


			<van-icon name="arrow-left" class="tabs-left-tip" @click="handleLeft" />
			<van-icon name="arrow" class="tabs-right-tip" @click="handleRight" />
		</view>
		<!-- 弹出拒绝的框 -->
		<!-- 		<van-dialog class="dialog" use-slot :show="showRejectDialog" show-cancel-button @confirm="clickSubmit"
			:before-close="beforeCloseDialog" @cancel="closeDialog">
			<view class="title">拒绝工单意见</view>
			<uv-textarea v-if="showRejectDialog" class="areas" placeholder="请输入" @input="rejectInputs">

			</uv-textarea>
		</van-dialog> -->
	</view>
</template>


<script setup>
	import {
		onLoad
	} from "@dcloudio/uni-app"
	import {
		ref,
		computed,
		reactive,
		onMounted,
		getCurrentInstance
	} from 'vue'
	import {
		reqOrderDetail,
		reqSaveOrderReport
	} from "@/api/operate.js"
	import imageUpload from "@/pages/components/pages/imageUpload/imageUpload.vue"


	// 使用 ref 定义基本类型数据
	const id = ref(''); // 工单详细信息需要的 id
	const title = ref('处理工单')
	const active = ref('光伏检查'); // tabs 绑定的数据
	const textareaMin = ref(1); // 拒绝原因-最少字数
	const textareaMax = ref(500); // 拒绝原因-最多字数
	const textareaTexts = ref('至少输入1个字~'); // 拒绝原因-实时输入事件
	const textareaLength = ref(null); // 拒绝原因-输入的长度
	const textareaValue = ref(''); // 拒绝原因-绑定的数据
	const remark = ref('');
	const flag = ref(true);
	const state = ref(null); // 当前状态
	const showStart = ref(false); // btn 按钮--处理人--开始处理
	const showComplete = ref(false); // btn 按钮--处理人--处理完成
	const showAgree = ref(false); // btn 按钮--验证人--同意
	const showReject = ref(false); // btn 按钮--验证人--拒绝
	const showStop = ref(false); // btn 按钮--发起人--终止
	const disabled = ref(false); // 是否禁用
	const showRejectDialog = ref(false); // 是否展示拒绝的 dialog 弹窗
	const orderItemList = ref([]) //当前选中的表单项
	const orderId = ref(null) //当前工单ID
	const uploadRefs = ref([]) //上传图片的ref
	// 存储每个项目的初始图片数据
	const allInitialFiles = ref({
		4: [{
				url: 'https://example.com/project1-img1.jpg',
				status: 'success'
			},
			{
				url: 'https://example.com/project1-img2.jpg',
				status: 'success'
			}
		],
		2: [{
			url: 'https://example.com/photo1.jpg',
			status: 'success',
			// name: 'photo1.jpg',
			// 可以添加其他自定义属性
			// id: '123',
			// type: 'image/jpeg'
		}]
	});
	// 使用 reactive 定义对象类型数据
	const gongdanDetail = reactive({}); // 工单详情数据
	const tabsList = reactive([]); // tabs 的数据
	const fileList = reactive([]); // 图片描述绑定的数据
	const fileArrTest = reactive([{
		url: 'https://gems-pros.com/resources/file/2023/12/15/RmaKbjBQ8LK3GE5oy4Dn.png',
		id: 'NRYW68POBwd9v41A3yMw',
	}, ]);
	const fileArr1 = reactive([]);
	const fileArr2 = reactive([]);
	const fileArr3 = reactive([]);

	const getGongdanInfo = async () => {
		try {
			let res = await reqOrderDetail(orderId.value);
			let data = res.data.data

			Object.assign(gongdanDetail, data);
			tabsList.splice(0, tabsList.length, ...data.workorderReportList);
			active.value = data.workorderReportList[0].name;
			state.value = data.state;

			const fileArr = [];
			tabsList.forEach((tab) => {
				tab.workorderReportItemList.forEach((item) => {
					if (item.type === 1 || item.type === 2) {
						item.textareaMin = 1;
						item.textareaMax = 520;
						item.textareaTexts = '至少输入1个字~';
						item.textareaLength = item.value ? item.value.length : 0;
						if (item.textareaLength <= item.textareaMin) {
							item.textareaTexts = '至少输入1个字~';
						} else {
							item.textareaTexts = ' ';
						}
					} else if (item.type === 4 && item.value) {
						fileArr.push({
							url: item.value,
							id: item.id,
							deletable: false
						});
					}
				});
			});

			fileArr1.splice(0, fileArr1.length, fileArr[0] || {});
			fileArr2.splice(0, fileArr2.length, fileArr[1] || {});
			fileArr3.splice(0, fileArr3.length, fileArr[2] || {});

			const name = tabsList[tabsList.length - 1].name;
			let localUserInfo = uni.getStorageSync('zh-h5-userInfo')
			const user = localUserInfo.userName;

			showStart.value =
				user === gongdanDetail.processor.userName && state.value === 1 && name === active.value;
			showComplete.value =
				user === gongdanDetail.processor.userName && state.value === 2 && name === active.value;
			showAgree.value =
				user === gongdanDetail.validator.userName && state.value === 3 && name === active.value;
			showReject.value =
				user === gongdanDetail.validator.userName && state.value === 3 && name === active.value;
			showStop.value =
				user === gongdanDetail.creater.userName &&
				state.value !== 5 &&
				state.value !== 8 &&
				name === active.value;
			disabled.value =
				user === gongdanDetail.processor.userName && state.value === 2 ? false : false;
		} catch (err) {
			console.error('获取工单详情数据失败，错误信息为：', err);
		}
	};
	//根据相对应的sort值进行传递
	const getInitialFiles = async (sort) => {
		let findItem = orderItemList.value.find(item => item.sort == sort && item.value != '')
		let fileItem = JSON.parse(findItem.value)
		if (Array.isArray(fileItem)) {
			return findItem ? JSON.parse(findItem.value) : [];
		} else {
			return findItem ? [JSON.parse(findItem.value)] : [];
		}
	}

	// 处理删除事件
	const handleDeleteFile = (itemIndex, {
		index,
		deletedFile
	}) => {
		try {
			const currentItem = orderItemList.value[itemIndex];
			if (!currentItem) return;

			// 解析当前图片数组
			let images = [];
			try {
				images = JSON.parse(currentItem.value || '[]');
			} catch (e) {
				console.error('解析图片数据失败:', e);
				images = [];
			}

			// 删除指定图片
			if (index >= 0 && index < images.length) {
				images.splice(index, 1);
				currentItem.value = JSON.stringify(images);
				console.log(`项目 ${itemIndex} 删除后的图片列表:`, images);
			}

		} catch (error) {
			console.error('处理删除图片时出错:', error);
		}
	}
	const bindSinglelineInput = (e, id) => {
		const value = e.target.value;
		tabsList.forEach((tab) => {
			tab.workorderReportItemList.forEach((item) => {
				if (item.id === id) {
					item.value = value;
				}
			});
		});
	}

	const handleFilesChange = (index, files) => {
		orderItemList.value[index] = files;
		// allFiles.value = orderItemList.value.flat();
	}


	//保存按钮
	const saveBtn = async () => {
		// console.log("保存参数", tabsList)
		try {
			await reqSaveOrderReport(tabsList)
			uni.showToast({
				title: '保存成功',

			})
			uni.navigateBack({
				delta: 1
			})
		} catch (error) {
			console.error(error)
		}
	}

	const handleUploadComplete = (itemIndex, {
		file
	}) => {
		try {
			if (!file?.data) {
				console.error('上传文件数据缺失');
				return;
			}

			const currentItem = orderItemList.value[itemIndex];
			if (!currentItem) {
				console.error(`索引 ${itemIndex} 的项目不存在`);
				return;
			}

			// 初始化或解析现有的图片列表
			let imageList = [];
			if (currentItem.value) {
				try {
					const parsedValue = JSON.parse(currentItem.value);
					imageList = Array.isArray(parsedValue) ? parsedValue : [parsedValue];
				} catch (e) {
					console.error('解析现有图片数据失败:', e);
					imageList = currentItem.value ? [currentItem.value] : [];
				}
			}

			// 处理Proxy对象 - 创建纯对象副本
			const fileData = JSON.parse(JSON.stringify(file.data));

			// 添加新文件数据（确保是纯对象）
			imageList.push({
				fileId: fileData.fileId || '',
				md5: fileData.md5 || '',
				originalFileName: fileData.originalFileName || '',
				url: fileData.url || '',
				fileName: fileData.fileName || ''
			});

			// 更新数据
			// currentItem.value = JSON.stringify(imageList);
			orderItemList.value[itemIndex].value = JSON.stringify(imageList)
			// 更好的日志输出
			console.log(`区域 ${itemIndex} 更新后的图片列表:`,
				JSON.parse(JSON.stringify(imageList)));

		} catch (error) {
			console.error('处理上传完成时出错:', error);
			// 可以添加错误上报逻辑
		}
	}
	// const handleUploadComplete = (itemIndex, {
	// 	file,
	// 	index
	// }) => {
	// 	console.log(`区域 ${itemIndex} 的文件 ${index} 上传完成:`, file);
	// 	let imgList = [];
	// 	// let a = orderItemList.value

	// 	if(orderItemList.value[itemIndex].value != ''){
	// 		 let imgFile = JSON.parse(orderItemList.value[itemIndex].value)

	// 		 	console.log(`文件-上传:`, JSON.parse(orderItemList.value[itemIndex].value));
	// 		imgList.push(imgFile)
	// 		imgList.push(file?.url)
	// 	}
	// 	console.log(`文件-list:`, imgList);
	// 	orderItemList.value[itemIndex].value = JSON.stringify(imgList)

	// }


	//取消按钮
	const cancelBtn = () => {
		uni.navigateBack({
			delta: 1
		})
	}

	const textareaInputs = (e, id) => {
		const value = e;
		const len = value.length;
		tabsList.forEach((tab) => {
			tab.workorderReportItemList.forEach((item) => {
				if (item.id === id) {
					item.value = value;
					item.textareaLength = len;
					item.textareaTexts = len <= item.textareaMin ? '至少输入1个字~' : ' ';
				}
			});
		});
	};


	const switchChange = (e, id) => {
		const value = e.target.checked;
		tabsList.forEach((tab) => {
			tab.workorderReportItemList.forEach((item) => {
				if (item.id === id) {
					item.value = value;
				}
			});
		});
	};

	const returnAvatar = (e, uploadId) => {
		const {
			url,
			type,
			fileList
		} = e.detail;
		tabsList.forEach((tab) => {
			tab.workorderReportItemList.forEach((item) => {
				if (item.id === uploadId) {
					item.value = type === '上传成功' ? url : fileList.length ? fileList[0].url : '';
				}
			});
		});
	};
	const onClick = (e) => {
		console.log("选中item->", e)
		orderItemList.value = e.workorderReportItemList

		active.value = e.name;
		const name = tabsList[tabsList.length - 1].name;

		let localUserInfo = uni.getStorageSync('zh-h5-userInfo')
		const user = localUserInfo.userName;

		showStart.value =
			user === gongdanDetail.processor.userName && state.value === 1 && name === active.value;
		showComplete.value =
			user === gongdanDetail.processor.userName && state.value === 2 && name === active.value;
		showAgree.value =
			user === gongdanDetail.validator.userName && state.value === 3 && name === active.value;
		showReject.value =
			user === gongdanDetail.validator.userName && state.value === 3 && name === active.value;
		showStop.value =
			user === gongdanDetail.creater.userName &&
			state.value !== 5 &&
			state.value !== 8 &&
			name === active.value;
		disabled.value =
			user === gongdanDetail.processor.userName && state.value === 2 ? false : false;
	};

	const handleBtn = async (e) => {
		const type = e.currentTarget.dataset.type;

		if (type === '开始处理') {
			try {
				const {
					data
				} = await httpRequest('/workorders/disposal', 'POST', {
					processorId: gongdanDetail.processor.userId,
					validatorId: gongdanDetail.validator.userId,
					workorderId: id.value,
					state: 2,
				});

				if (data.success) {
					uni.showToast({
						title: '开始处理工单',
						icon: 'none',
						duration: 2000,
					});
					getGongdanInfo();
				}
			} catch (err) {
				console.error('点击接受失败，错误信息为：', err);
				uni.showToast({
					title: err.data.message,
					icon: 'none',
					duration: 2000,
				});
			}
		} else if (type === '处理完成') {
			try {
				const {
					data
				} = await httpRequest('/workorders/disposal', 'POST', {
					processorId: gongdanDetail.processor.userId,
					validatorId: gongdanDetail.validator.userId,
					workorderId: id.value,
					state: 3,
				});

				if (data.success) {
					const {
						data: reportData
					} = await httpRequest('/workorders/disposal/report', 'PUT', tabsList);

					if (reportData.success) {
						uni.showToast({
							title: '处理完成~',
							icon: 'none',
							duration: 2000,
						});
						getGongdanInfo();
					}
				}
			} catch (err) {
				console.error('点击接受失败，错误信息为：', err);
			}
		} else if (type === '终止') {
			uni.showModal({
				title: '确定要终止工单吗?',
				content: '注意：终止工单将导致该工单永久失效。',
				success: async (res) => {
					if (res.confirm) {
						try {
							const {
								data
							} = await httpRequest('/workorders/disposal', 'POST', {
								processorId: gongdanDetail.processor.userId,
								validatorId: gongdanDetail.validator.userId,
								workorderId: id.value,
								state: 8,
							});

							if (data.success) {
								uni.showToast({
									title: '终止工单成功~',
									icon: 'none',
									duration: 2000,
								});
								getGongdanInfo();
							}
						} catch (err) {
							console.error('点击接受失败，错误信息为：', err);
						}
					}
				},
			});
		} else if (type === '同意') {
			try {
				const {
					data
				} = await httpRequest('/workorders/disposal', 'POST', {
					processorId: gongdanDetail.processor.userId,
					validatorId: gongdanDetail.validator.userId,
					workorderId: id.value,
					state: 5,
					operation: 1,
				});

				if (data.success) {
					uni.showToast({
						title: '通过,工单已完成~',
						icon: 'none',
						duration: 2000,
					});
					getGongdanInfo();
					uni.navigateBack({
						delta: 1,
					});
				}
			} catch (err) {
				console.error('点击接受失败，错误信息为：', err);
			}
		} else if (type === '拒绝') {
			showRejectDialog.value = true;
		}
	};

	const closeDialog = () => {
		showRejectDialog.value = false;
		remark.value = '';
		textareaLength.value = null;
	};

	const clickSubmit = async () => {
		if (remark.value === '') {
			uni.showToast({
				title: '意见不能为空~',
				icon: 'none',
				duration: 2000,
			});
			showRejectDialog.value = true;
		} else {
			try {
				const {
					data
				} = await httpRequest('/workorders/disposal', 'POST', {
					processorId: gongdanDetail.processor.userId,
					validatorId: gongdanDetail.validator.userId,
					workorderId: id.value,
					state: 1,
					operation: 0,
					remark: remark.value,
				});

				if (data.success) {
					uni.showToast({
						title: '拒绝成功~',
						icon: 'none',
						duration: 2000,
					});
					showRejectDialog.value = false;
					remark.value = '';
					textareaLength.value = null;
					getGongdanInfo();
				}
			} catch (err) {
				console.error('点击接受失败，错误信息为：', err);
			}
		}
	};
	// 输入框内容处理
	const rejectInputs = (e) => {
		const value = e.target.value;
		const len = value.length;
		remark.value = value;

		// 最少字数限制
		if (len <= textareaMin.value) {
			textareaTexts.value = '至少输入1个字~';
		} else if (len > textareaMin.value) {
			textareaTexts.value = '';
		}

		// 最多字数限制
		if (len > textareaMax.value) return;
		textareaLength.value = len; // 当前字数
	};

	// 切换到下一项
	const handleRight = () => {
		const currentIndex = tabsList.value.findIndex((item) => item.name === active.value);

		if (currentIndex !== -1 && currentIndex < tabsList.value.length - 1) {
			active.value = tabsList.value[currentIndex + 1].name;
		} else {
			uni.showToast({
				title: '已经是最后一项了',
				icon: 'none',
				duration: 2000,
			});
		}
	};

	// 切换到上一项
	const handleLeft = () => {
		const currentIndex = tabsList.value.findIndex((item) => item.name === active.value);

		if (currentIndex > 0) {
			active.value = tabsList.value[currentIndex - 1].name;
		} else {
			uni.showToast({
				title: '已经是第一项了',
				icon: 'none',
				duration: 2000,
			});
		}
	};


	onMounted(() => {
		// getGongdanInfo();
	});
	onLoad((option) => {
		const instance = getCurrentInstance().proxy;
		const eventChannel = instance.getOpenerEventChannel()
		orderId.value = option.id
		getGongdanInfo().then(() => {
			onClick(tabsList[0])
		})
		// eventChannel.on('getAlarmId', (data) => {
		// 	getDetail(option.alarmId)
		// })
	})
</script>

<style lang="scss" scoped>
	.container {
		padding: 0 20rpx;

		.tabs {
			::v-deep {
				.uv-tabs__wrapper__nav {
					justify-content: center;
				}

				.uv-tabs__wrapper__nav__line {
					transform: translate(0px) !important;
				}
			}

			.itemMain {
				.multilineInput {
					margin: 12rpx 0;

					.txt {
						margin-bottom: 10rpx;
					}
				}

				.img {
					.txt {
						margin-bottom: 10rpx;
					}
				}
			}
		}
	}
</style>